package com.zwl.chengguangservice.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zwl.chengguangservice.annotation.EnableAuth;
import com.zwl.chengguangservice.dao.OrderMapper;
import com.zwl.chengguangservice.dao.UserMapper;
import com.zwl.chengguangservice.entity.Order;
import com.zwl.chengguangservice.entity.Result;
import com.zwl.chengguangservice.entity.User;
import com.zwl.chengguangservice.pojo.CreateOrderDTO;
import com.zwl.chengguangservice.utlis.TokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/** @date 2022/02/19 */
@RestController
@RequestMapping("/v1/order")
public class OrderController {
    @Resource
    private UserMapper userMapper;


    @Resource
    private OrderMapper orderMapper;

    @PostMapping
    @EnableAuth
    public Result<Object> createOrder(@RequestBody CreateOrderDTO createOrderDTO, HttpServletRequest request) {
        Order order = new Order();
        BeanUtils.copyProperties(createOrderDTO, order);
        order.setStateId(0);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        String username = TokenUtil.getAccount(request.getHeader("admin-token"));
        User user =
                userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        if (user == null) {
            return new Result<>("请先登录");
        }

        order.setCreateUserId(user.getUserId());
        orderMapper.insert(order);

        return new Result<>(true);
    }

    @GetMapping("/{id}")
    public Result<Order> getOrderById(@PathVariable("id") Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return new Result<>("订单不存在", 500, null);
        }

        if (order.getExpiredAt().before(new Date())) {
            order.setStateId(3);
            orderMapper.updateById(order);
        }

        return new Result<>(order);
    }
}
